package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"project/pkg"
	"strings"
	"time"

	"project/projectapi/internal/svc"
	"project/projectapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, header, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Message: "文件获取失败",
			Code:    500,
			Data:    nil,
		}, nil
	}
	if header.Size > 10*1024*1024 {
		return &types.Response{
			Message: "文件大小不能超过10mb",
			Code:    500,
			Data:    nil,
		}, nil
	}

	get := req.Form.Get("who")
	lower := strings.ToLower(filepath.Ext(header.Filename))
	dir := "image"
	if get == "1" {
		if lower != ".png" && lower != ".jpeg" {
			return &types.Response{
				Message: "文件后缀只能为phg或jpeg",
				Code:    500,
				Data:    nil,
			}, nil
		}

	}
	filename := dir + "/" + time.Now().Format(time.DateTime) + lower
	if get == "2" {
		dir = "video"
		if lower != ".mp4" && lower != ".mp5" {
			return &types.Response{
				Message: "文件后缀只能为mp4或mp5",
				Code:    500,
				Data:    nil,
			}, nil
		}
		filename = dir + "/" + time.Now().Format(time.DateTime) + lower
	}
	if get == "3" {
		dir = "file"
		if lower != ".doc" && lower != ".ppt" {
			return &types.Response{
				Message: "文件后缀只能为doc或ppt",
				Code:    500,
				Data:    nil,
			}, nil
		}
		filename = dir + "/" + time.Now().Format(time.DateTime) + lower
	}

	yun, err := pkg.QiNiuYun(file, header, filename)
	if err != nil {
		return &types.Response{
			Message: "文件上传失败" + err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "文件上传成功",
		Code:    200,
		Data:    yun,
	}, nil
}
